<template>
	<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10" v-bind="$attrs"></u-upload>
</template>
<script setup>
	import {
		ref,
		watch
	} from 'vue';
	import {
		apiBaseURL
	} from '@/config/index.js'
	import {
		getAuthorization
	} from '@/router/auth.js';
	const token = getAuthorization('accessToken')
	const emits = defineEmits(['update:modelValue']);
	/***
	 * props
	 * @property {Array} modelValue v-model绑定的值，
	 */
	const props = defineProps({
		modelValue: [Array, String],
	});
	// watch(
	// 	() => props.modelValue,
	// 	(val) => {
	// 		if (val) {
	// 			fileList.value = val?.map((item) => ({
	// 				id: item.id,
	// 				url: item.downloadUrl,
	// 				fileName: item.fileName,
	// 				fileSizeFormat: item.fileSizeFormat,
	// 				fileSize: item.fileSize,
	// 				fileSuffix: item.fileSuffix
	// 			})) || [];
	// 		}
	// 	});
	let fileList = ref([]);
	// 删除图片
	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	};
	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			console.log('result', result);
			let item = fileList.value[fileListLen];
			fileList.value.splice(fileListLen, 1, {
				status: 'success',
				url: result.downloadUrl,
				id: result.id,
				downloadUrl: result.downloadUrl,
				fileName: result.fileName.split('.')[0],
				fileSizeFormat: result.fileSizeFormat,
				fileSize: result.fileSize
			});
			fileListLen++;
		}
	};
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let result = uni.uploadFile({
				url: apiBaseURL + '/rdfile/data/upload', // 仅为测试 后续根据实际环境配置
				filePath: url,
				name: 'file',
				header: {
					'Authorization': token,
					'gc-authentication': token
				},
				success: (res) => {
					setTimeout(() => {
						resolve(JSON.parse(res.data).data);
					}, 500);
				},
			});
		});
	};
	watch(() => fileList.value, (val) => {
		emits('update:modelValue', val)
	}, {
		deep: true
	})
</script>
<style>
</style>